package com.alibaba.citrus.ots.forecast.repository.impl;

import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.forecast.functions.forecastorder.constants.ForecastConstants;
import com.alibaba.citrus.ots.forecast.repository.ForecastOrderLineWriteRepository;
import com.alibaba.citrus.ots.forecast.repository.impl.converter.ForecastOrderRepositoryConverter;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.otsforecastsales.domian.forecastorderline.dto.*;
import com.epoch.app.otsforecastsales.domian.forecastorderline.model.ForecastOrderLine;
import com.epoch.app.otsforecastsales.domian.forecastorderline.service.ForecastOrderLineService;
import com.epoch.app.otsforecastsales.dto.request.DeleteForecastLineDetailRequest;
import com.epoch.app.otsforecastsales.dto.request.LoseFocusSaveForecastLineOrderRequest;
import com.epoch.app.otsforecastsales.enums.ForecastStatusEnum;
import com.epoch.app.otsforecastsales.sdo.ForecastOrderLineSDO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: qiaojiange
 * @create: 2021/09/15
 * @Description 请描述类的业务用途
 */
@Service
public class ForecastOrderLineWriteRepositoryImpl implements ForecastOrderLineWriteRepository {
    @Resource
    ForecastOrderLineService forecastOrderLineService;
    private static final Log log = Log.getLogger(ForecastOrderLineWriteRepositoryImpl.class);

    /**
     * 保存预报子单
     * @param forecastOrderLineSDO
     * @return
     */
    @Override
    @RepositoryInvoker
    public String save(ForecastOrderLineSDO forecastOrderLineSDO) {
        ForecastOrderLine forecastOrderLine = new ForecastOrderLine();
        if(null!=forecastOrderLineSDO.getStatus()){
            forecastOrderLine.setStatus(forecastOrderLineSDO.getStatus());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getScItemId())){
            forecastOrderLine.setScItemId(forecastOrderLineSDO.getScItemId());//商品id
            //保存子单商品名称
            forecastOrderLine.setScItemTitle(forecastOrderLineSDO.getScItemTitle());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getQuantity())){//数量
            forecastOrderLine.setQuantity(forecastOrderLineSDO.getQuantity());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getDetailRemark())){//备注
            forecastOrderLine.setDetailRemark(forecastOrderLineSDO.getDetailRemark());
        }
        //创建子单先设置其主单id
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getMainOrderId())){
            forecastOrderLine.setMainOrderId(forecastOrderLineSDO.getMainOrderId());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getCreatorId())) {
            forecastOrderLine.setCreatorId(forecastOrderLineSDO.getCreatorId());
            forecastOrderLine.setCreatorName(forecastOrderLineSDO.getCreatorName());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getModifierId())) {
            forecastOrderLine.setModifierId(forecastOrderLineSDO.getModifierId());
            forecastOrderLine.setModifierName(forecastOrderLineSDO.getModifierName());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getMainOrderBizId())) {
            forecastOrderLine.setMainOrderBizId(forecastOrderLineSDO.getMainOrderBizId());
        }
        if (Objects.nonNull(forecastOrderLineSDO.getTotalFee())) {
            forecastOrderLine.setTotalFee(forecastOrderLineSDO.getTotalFee());
        }

        forecastOrderLine.setDealStatus(forecastOrderLineSDO.getDealStatus());//队列状态 0
        forecastOrderLine.setSerialNumber(forecastOrderLineSDO.getSerialNumber());//行号 TODO
        forecastOrderLine.setSaleUnit(forecastOrderLineSDO.getSaleUnit());
        forecastOrderLine.setInventoryUnit(forecastOrderLineSDO.getInventoryUnit());//库存单位 TODO
        forecastOrderLine.setInventoryUnitCode(forecastOrderLineSDO.getInventoryUnitCode());
        forecastOrderLine.setSaleUnitcode(forecastOrderLineSDO.getSaleUnitCode());
        forecastOrderLine.setWarehouseArea(forecastOrderLineSDO.getWarehouseArea());
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getUnitConvert())){
            forecastOrderLine.setUnitConvert(forecastOrderLineSDO.getUnitConvert());//单位转换关系
        }
        if (null!=forecastOrderLineSDO.getUnitPrice()){
            forecastOrderLine.setUnitPrice(forecastOrderLineSDO.getUnitPrice());//常规单价
            if (StringUtils.isNotBlank(forecastOrderLineSDO.getQuantity())){
                String quantity = forecastOrderLineSDO.getQuantity();
                forecastOrderLine.setTotalFee(Integer.parseInt(quantity)*forecastOrderLineSDO.getUnitPrice());//常规总金额
            }
        }

        Map<String, Object> features = forecastOrderLineSDO.getFeatures()==null?new HashMap<>():forecastOrderLineSDO.getFeatures();
        features.put(ForecastConstants.GOODS_CODE, forecastOrderLineSDO.getGoodsCode());
        features.put(ForecastConstants.ACTIVITY_TAG,0);
        features.put(ForecastConstants.ACTIVITY_NUMBER,forecastOrderLineSDO.getActivityNumber());
        features.put(ForecastConstants.REPLENISHMENT_ACTIVITY_VERSION,forecastOrderLineSDO.getActivityVersion());
        features.put(ForecastConstants.ACTIVITY_PRICE_REMARK, forecastOrderLineSDO.getActivityPriceRemark());
        features.put(ForecastConstants.REPLENISHMENT_ACTIVITY_REMAINING_FEE,forecastOrderLineSDO.getActivityRemainingFee());
        features.put(ForecastConstants.REPLENISHMENT_ACTIVITY_REMAINING_QUANTITY,forecastOrderLineSDO.getActivityRemainingQuantity());
        features.put(ForecastConstants.REPLENISHMENT_INTENSITY_OF_ACTIVITY_DESC,forecastOrderLineSDO.getIntensityOfActivityDesc());
        forecastOrderLine.setFeatures(JSONObject.toJSONString(features));
        if(StringUtils.isNotEmpty(forecastOrderLineSDO.getActivityName())){
            forecastOrderLine.setActivityName(forecastOrderLineSDO.getActivityName());
        }
        if(StringUtils.isNotEmpty(forecastOrderLineSDO.getActivityCode())){
            forecastOrderLine.setActivityCode(forecastOrderLineSDO.getActivityCode());
        }
        forecastOrderLine.setScItemOutCode(forecastOrderLineSDO.getGoodsCode());
        forecastOrderLine.setCustomerCode(forecastOrderLineSDO.getCustomerCode());
        forecastOrderLine.setCategoryChildCode(forecastOrderLineSDO.getCategoryChildCode());
        forecastOrderLine.setCategoryChildDesc(forecastOrderLineSDO.getCategoryChildDesc());
        forecastOrderLine.setCategoryCode(forecastOrderLineSDO.getCategoryCode());
        forecastOrderLine.setCategoryDesc(forecastOrderLineSDO.getCategoryDesc());
        forecastOrderLine.setFirstCategoryCode(forecastOrderLineSDO.getFirstCategoryCode());
        forecastOrderLine.setFirstCategoryDesc(forecastOrderLineSDO.getFirstCategoryDesc());
        forecastOrderLine.setSecondCategoryCode(forecastOrderLineSDO.getSecondCategoryCode());
        forecastOrderLine.setSecondCategoryDesc(forecastOrderLineSDO.getSecondCategoryDesc());
        forecastOrderLine.setActualTotalReplyAmount(forecastOrderLineSDO.getActualTotalReplyAmount());
//        forecastOrderLine.setPredictReplyAmount(1000);//预计回复数量 TODO
        CreateForecastOrderLineResponse response = forecastOrderLineService.createForecastOrderLine(forecastOrderLine);
        String lastInsertId = response.getLastInsertId();
        if (StringUtils.isEmpty(lastInsertId)) {
            log.error("ForecastOrderLineWriteRepositoryImpl#save_fail");
        }
        return lastInsertId;
    }
    /**
     *更改预报子单
     */
    @Override
    @RepositoryInvoker
    public Integer modify(ForecastOrderLineSDO forecastOrderLineSDO) {
        ForecastOrderLine forecastOrderLine = new ForecastOrderLine();
        if (forecastOrderLineSDO.getId()==null){
            return null;
        }
        forecastOrderLine.setId(forecastOrderLineSDO.getId());
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getScItemId())){
            forecastOrderLine.setScItemId(forecastOrderLineSDO.getScItemId());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getQuantity())) {
            forecastOrderLine.setQuantity(forecastOrderLineSDO.getQuantity());
        }

        forecastOrderLine.setDetailRemark(forecastOrderLineSDO.getDetailRemark());

        if (StringUtils.isNotBlank(forecastOrderLineSDO.getSaleUnit())) {
            forecastOrderLine.setSaleUnit(forecastOrderLineSDO.getSaleUnit());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getSaleUnitCode())){
            forecastOrderLine.setSaleUnitcode(forecastOrderLineSDO.getSaleUnitCode());
        }
        if (StringUtils.isNotBlank(forecastOrderLineSDO.getUnitConvert())){
            forecastOrderLine.setUnitConvert(forecastOrderLineSDO.getUnitConvert());
        }
        if (null!=forecastOrderLineSDO.getSerialNumber()){
            forecastOrderLine.setSerialNumber(forecastOrderLineSDO.getSerialNumber());
        }
        if (MapUtils.isNotEmpty(forecastOrderLineSDO.getFeatures())) {
            forecastOrderLine.setFeatures(JSONObject.toJSONString(forecastOrderLineSDO.getFeatures()));
        }
        if (Objects.nonNull(forecastOrderLineSDO.getStatus())){
            forecastOrderLine.setStatus(forecastOrderLineSDO.getStatus());
        }
        if (Objects.nonNull(forecastOrderLineSDO.getTotalFee())) {
            forecastOrderLine.setTotalFee(forecastOrderLineSDO.getTotalFee());
        }
        UpdateForecastOrderLineResponse updateForecastOrderLineResponse = forecastOrderLineService.updateForecastOrderLine(forecastOrderLine);
        Integer count = updateForecastOrderLineResponse.getCount();
        if (0 == count) {
            log.error("ForecastOrderLineWriteRepositoryImpl#modify_fail");
        }
        return count;
    }

    @Override
    @RepositoryInvoker
    public Boolean submit(ForecastOrderLineSDO forecastOrderLineSDO) {
        LoadForecastOrderLineRequest loadForecastOrderLineRequest=new LoadForecastOrderLineRequest();
        loadForecastOrderLineRequest.setId(String.valueOf(forecastOrderLineSDO.getId()));
        ForecastOrderLine forecastOrderLine = forecastOrderLineService.loadForecastOrderLine(loadForecastOrderLineRequest);
        forecastOrderLine.setId(forecastOrderLineSDO.getId());
        if(null!=(forecastOrderLineSDO.getStatus())) {
            forecastOrderLine.setStatus(forecastOrderLineSDO.getStatus());
        }
        if(null!=(forecastOrderLineSDO.getDealStatus())) {
            forecastOrderLine.setDealStatus(forecastOrderLineSDO.getDealStatus());
        }
        forecastOrderLine.setModifierName(forecastOrderLineSDO.getModifierName());
        forecastOrderLine.setMainOrderId(forecastOrderLineSDO.getMainOrderId());

        forecastOrderLine.setFeatures(JSONObject.toJSONString(forecastOrderLineSDO.getFeatures()));

        UpdateForecastOrderLineResponse updateForecastOrderLineResponse = forecastOrderLineService.updateForecastOrderLine(forecastOrderLine);
        Integer count = updateForecastOrderLineResponse.getCount();
        if (0 == count) {
            log.error("ForecastOrderLineWriteRepositoryImpl#submit_fail");
            return false;
        }
        return true;
    }
    @Override
    @RepositoryInvoker
    public Boolean update(ForecastOrderLineSDO forecastOrderLineSDO) {
        ForecastOrderLine forecastOrderLine = ForecastOrderRepositoryConverter.toForecastOrderLine(forecastOrderLineSDO);
        Integer count = 0;
        if (StringUtils.isNotBlank(forecastOrderLine.getFeatures())) {
            String features = forecastOrderLine.getFeatures();
            JSONObject jsonObject = JSON.parseObject(features);
            if ("true".equals(jsonObject.get(ForecastConstants.REMOVE_ACTIVITY_PRICE))) {
                jsonObject.remove(ForecastConstants.REMOVE_ACTIVITY_PRICE);
                forecastOrderLine.setFeatures(jsonObject.toJSONString());
                UpdateForecastOrderLineForNullActivityInfoResponse nullActivityInfoResponse = forecastOrderLineService.updateForecastOrderLineForNullActivityInfo(forecastOrderLine);
                count = nullActivityInfoResponse.getCount();
                return Objects.nonNull(count) && count != 0;
            }
        }
        UpdateForecastOrderLineResponse updateForecastOrderLineResponse = forecastOrderLineService.updateForecastOrderLine(forecastOrderLine);
        count = updateForecastOrderLineResponse.getCount();
        if (0 == count) {
            return false;
        }
        return true;
    }
    @Override
    @RepositoryInvoker(printLog = false)
    public Boolean updateForAnalysis(ForecastOrderLineSDO forecastOrderLineSDO) {
        ForecastOrderLine forecastOrderLine = ForecastOrderRepositoryConverter.toForecastOrderLine(forecastOrderLineSDO);
//        log.info("打印下子单行：{}", forecastOrderLine);
        UpdateForecastOrderLineResponse updateForecastOrderLineResponse = forecastOrderLineService.updateForecastOrderLine(forecastOrderLine);
        Integer count = updateForecastOrderLineResponse.getCount();
        if (0 == count) {
            return false;
        }
        return true;
    }

    @Override
    @RepositoryInvoker
    public Boolean updateReplyQuantity(ForecastOrderLineSDO forecastOrderLineSDO) {
        LoadForecastOrderLineRequest loadForecastOrderLineRequest=new LoadForecastOrderLineRequest();
        loadForecastOrderLineRequest.setId(String.valueOf(forecastOrderLineSDO.getId()));
        ForecastOrderLine forecastOrderLine = forecastOrderLineService.loadForecastOrderLine(loadForecastOrderLineRequest);
        forecastOrderLine.setId(forecastOrderLineSDO.getId());
        forecastOrderLine.setPredictReplyAmount(forecastOrderLineSDO.getPredictReplyAmount());
        forecastOrderLine.setGoodsProductationTime(forecastOrderLineSDO.getGoodsProductationTime());
        forecastOrderLine.setDetailRemark(forecastOrderLineSDO.getDetailRemark());
        UpdateForecastOrderLineResponse updateForecastOrderLineResponse = forecastOrderLineService.updateForecastOrderLine(forecastOrderLine);
        Integer count = updateForecastOrderLineResponse.getCount();
        if (0 == count) {
            return false;
        }
        return true;
    }


    /**
     * 批量修改预报子订单状态
     *
     * @param batchAnalysisOrdersRequest
     * @return
     */
    @Override
    @RepositoryInvoker
    public Boolean batchUpdateStatus(List<ForecastOrderLineSDO> batchAnalysisOrdersRequest) {
        BatchUpdateStatusRequest batchLoadListResponse=new BatchUpdateStatusRequest();
        List<String> ids = Nullable.stream(batchAnalysisOrdersRequest).map(it -> it.getId().toString()).collect(Collectors.toList());
        List<Integer> status = Nullable.stream(batchAnalysisOrdersRequest).map(it -> it.getStatus()).collect(Collectors.toList());
        batchLoadListResponse.setIds(ids);
        batchLoadListResponse.setStatus(status.get(0));
        Object  o= forecastOrderLineService.batchUpdateStatus(batchLoadListResponse);
        return true;

    }




    /**
     * 批量修改预报订单
     * @param forecastOrderLineSDOList
     * @return
     */

    @Override
    public Boolean batchUpdateForecastOrderLine(List<ForecastOrderLineSDO> forecastOrderLineSDOList) {
        List<ForecastOrderLine> collect = Nullable.stream(forecastOrderLineSDOList).map(ForecastOrderRepositoryConverter::toForecastOrderLine).collect(Collectors.toList());
        for (ForecastOrderLine forecastOrderLine :collect ) {
            UpdateForecastOrderLineResponse updateForecastOrderLineResponse = forecastOrderLineService.updateForecastOrderLine(forecastOrderLine);
        }
        return true;
    }
    /*
    失焦保存 王成
     */
    @Override
    public Integer loseFocusSave(LoseFocusSaveForecastLineOrderRequest request) {
        ForecastOrderLine forecastOrderLine = new ForecastOrderLine();
        forecastOrderLine.setId(request.getId());
        //判断是不是草稿状态的失焦保存 设置其状态
        if(StringUtils.equals(request.getPageMode(),"draft")){
            forecastOrderLine.setStatus(ForecastStatusEnum.DRAFT.getNumValue());
        }else{
            forecastOrderLine.setStatus(ForecastStatusEnum.WAITING_FOR_REPLY.getNumValue());
        }
//        BeanUtils.copyProperties(request,forecastOrderLine);
        if (StringUtils.isNotBlank(request.getOrderId())){
            forecastOrderLine.setMainOrderId(request.getOrderId());
        }
        if (StringUtils.isNotBlank(request.getQuantity())){
            forecastOrderLine.setQuantity(request.getQuantity());
        }
        if (StringUtils.isNotBlank(request.getDetailRemark())){
            forecastOrderLine.setDetailRemark(request.getDetailRemark());
        }
        UpdateForecastOrderLineResponse updateForecastOrderLineResponse = forecastOrderLineService.updateForecastOrderLine(forecastOrderLine);
        Integer count = updateForecastOrderLineResponse.getCount();
        return 1;
    }
    /*
    删除子单 王成
     */
    @Override
    public Integer deleteForecastLine(DeleteForecastLineDetailRequest request) {
        List<String> ids = request.getIds();
        BatchDeleteByIdsRequest batchDeleteByIdsRequest = new BatchDeleteByIdsRequest();
        batchDeleteByIdsRequest.setIds(ids);
        BatchDeleteByIdsResponse batchDeleteByIdsResponse = forecastOrderLineService.batchDeleteByIds(batchDeleteByIdsRequest);
        Integer count = batchDeleteByIdsResponse.getCount();
        return count;
    }

    @Override
    public Boolean batchUpdateCollectStatus(UpdateCollectStatusRequest request){
        if (CollectionUtils.isEmpty(request.getIds())){
            return Boolean.FALSE;
        }
        return forecastOrderLineService.updateCollectStatus(request).getCount()
                == request.getIds().size();
    }
}
